#coding:utf-8
from model import GuestBookModel, datavalid
from config import get_webpage_strings, banner_list
from mako.lookup import TemplateLookup
from bottle import request, redirect
from pager import Pager
from gravatar import get_gravatar
import datetime



def list_entry(num):
    webpage = get_webpage_strings(now=u'留言板')
    guestbooklookup = TemplateLookup(directories=['./theme/'+self.webpage['theme']+'/templates'], input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace')    
    banner = banner_list
    entry_list = GuestBookModel.all().order('-__key__')
    if not entry_list:
        return 'No Result'
    else:
        #此处留待修改，加入主题功能后修改此处
        guestbooktemplate = guestbooklookup.get_template('guestbook.tpl')
        gstbkpg = Pager(query=entry_list,page_length=webpage['numofgreeting'])
        entry_list2, links = gstbkpg.fetch(curpage=num)
        a = { 'webpage': webpage, 'banners': banner, 'greetings': entry_list2, 'gstbkpg': gstbkpg, 'link': links, 'num': num}
        return guestbooktemplate.render(**a)
    
    
def add_entry(baseurl='/'):
    now = datetime.datetime.now()
    webpage = get_webpage_strings(now=u'留言板')
    if not baseurl.endswith('/'):
        baseurl = baseurl + '/'
    addin = GuestBookModel()
    #验证数据并赋值保存
    result = {
       'author': datavalid(data=request.forms.get('author'), datatype='author'),
       'email': datavalid(data=request.forms.get('email'), datatype='email'),
       'content': datavalid(data=request.forms.get('content'), datatype='content'),
       'url': datavalid(data=request.forms.get('webpage'), datatype='url'),
    }
    if result['author']:        
        if result['email']:            
            if result['content']:                
                if result['url']:
                    addin.content = result['content']
                    addin.email = result['email']
                    addin.author = result['author']
                    addin.webpage = result['url']
                    addin.avatarurl = get_gravatar(result['email'])
                    addin.time = now + datetime.timedelta(hours=webpage['timeoffset'])
                    addin.save()
                    redirect(baseurl)      #成功后跳转回第一页
    #失败后显示失败页
    redirect(baseurl+'fail')

    
